from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from datetime import datetime
from app1.models import Emp, Dept
from app1.util.pagination import Pagination
import random
import string

def emp_list(request):
    '''查询员工信息'''

    # dept_list = Dept.objects.all()
    # fnames = ['张','万','王','李','五','武','吴','赵','钱','孙','宋','韩']
    # lnames = string.digits+string.ascii_lowercase
    # for i in range(200):
    #     Emp.objects.create(ename='{}{}'.format(fnames[random.randint(0,len(fnames)-1)],"".join(random.choices(lnames,k=3)))
    #                        ,sal=random.randint(800,10000)
    #                        ,hiredate="{}-{}-{}".format(random.randint(1990,2024),random.randint(1,12),random.randint(1,29))
    #                        ,dept=dept_list[random.randint(0,len(dept_list)-1)]
    #                        )


    query_param = {}
    q = request.GET.get('q')
    if q:
        query_param['ename__contains'] = q
    queryset = Emp.objects.filter(**query_param)
    page = Pagination(request,queryset)
    return render(request,'emp/emp_list.html',{'emp_list':page.get_page_result(),'page_str':page.get_page_str()})


def emp_add(request):
    if request.method == 'GET':
        dept_list = Dept.objects.all()
        return render(request, 'emp/emp_add.html', {'dept_list': dept_list})

    ename = request.POST.get('ename')
    sal = request.POST.get('sal')
    hiredate_str = request.POST.get('hiredate')
    deptno = request.POST.get('deptno')

    # 转换日期格式
    try:
        # 尝试解析为 YYYY-MM-DD 格式
        hiredate = datetime.strptime(hiredate_str, '%Y-%m-%d').date()
    except ValueError:
        try:
            # 尝试解析为 MM/DD/YYYY 格式
            hiredate = datetime.strptime(hiredate_str, '%m/%d/%Y').date()
        except:
            return HttpResponse("日期格式错误，请使用 YYYY-MM-DD 格式", status=400)

    # 创建员工记录
    Emp.objects.create(ename=ename, sal=sal, hiredate=hiredate, dept_id=deptno)
    return redirect(reverse('emp_list'))

def emp_update(request):
    if request.method=='GET':
        empno = request.GET.get('empno')
        emp = Emp.objects.filter(empno=empno).first()

        dept_list = Dept.objects.all()
        return render(request,'emp/emp_update.html',{'emp':emp,'dept_list':dept_list})
    empno = request.POST.get('empno')
    ename = request.POST.get('ename')
    sal = request.POST.get('sal')
    hiredate = request.POST.get('hiredate')
    deptno = request.POST.get('deptno')
    Emp.objects.filter(empno=empno).update(ename=ename,sal=sal,hiredate=hiredate,dept_id=deptno)
    return redirect(reverse('emp_list'))

def emp_delete(request):
    empno = request.GET.get('empno')
    Emp.objects.filter(empno=empno).delete()
    return redirect(reverse('emp_list'))

